<template>
  <div class="phone">
    <el-form
      ref="loginFormRef"
      :model="loginFormData"
      :rules="loginFormRules"
      @keyup.enter="handleLogin"
    >
      <el-form-item prop="phone">
        <el-input
          v-model.trim="loginFormData.phone"
          placeholder="手机号"
          type="text"
          tabindex="1"
          :prefix-icon="Phone"
          size="large"
          @blur="() => handleBlur()"
          @focus="() => handleFocus()"
        />
      </el-form-item>
      <el-form-item prop="code">
        <div class="vertify-code">
          <el-input
            v-model.trim="loginFormData.code"
            placeholder="验证码"
            type="text"
            tabindex="2"
            :prefix-icon="Lock"
            size="large"
            @blur="() => handleBlur()"
            @focus="() => handleFocus()"
          />
          <el-button
            class="get-btn"
            size="large"
            type="primary"
          >获取验证码</el-button>
        </div>

      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginPhoneRequestData, LoginResponseData } from '@/types/login.d'
import { ElMessage } from 'element-plus'
import { Lock, Phone } from '@element-plus/icons-vue'
import { accountLogin } from '@/services/user'
import { useUserStore } from '@/pinia/stores/user'

const props = defineProps({
  handleBlur: {
    type: Function,
    required: true
  },
  handleFocus: {
    type: Function,
    required: true
  },
  updateLoading: {
    type: Function,
    required: true
  }
})

/** 登录表单Form的引用 */
const loginFormRef = ref<FormInstance | null>(null)

/** 登录表单数据 */
const loginFormData: LoginPhoneRequestData = reactive({
  phone: 'admin',
  code: '12345678'
})
/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  phone: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const userStore = useUserStore()
/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error('表单校验不通过')
      return
    }
    props.updateLoading(true)
    accountLogin({
      phone: loginFormData.phone,
      code: loginFormData.code
    })
      .then(({ data }: LoginResponseData) => {
        console.log(data)
        userStore.setToken(data.token)
        name.value = data.name
        // router.push("/")
      })
      .catch((error) => {
        loginFormData.code = ''
        console.log(error)
      })
      .finally(() => {
        props.updateLoading(false)
      })
  })
}

defineExpose({ handleLogin })
</script>

<style lang="scss" scoped>
.vertify-code {
  display: flex;
  width: 100%;
  .get-btn {
    margin-left: 8px;
  }
}
</style>
